import { Component } from "react";
import axios from "axios";
import "./global.scss";

interface IProduct {
  id: number;
  imgSrc: string;
  productName: string;
  price: number;
  count: number;
}

interface IProps {}

interface IState {
  products: IProduct[];
}

export default class App extends Component<IProps, IState> {
  // 初始化 state 数据
  state: Readonly<IState> = {
    products: [],
  };

  /**
   * 请求数据的方法
   */
  fetchData = () => {
    axios<IProduct[]>({
      url: "http://localhost:3000/products",
      method: "GET",
      params: {},
    })
      .then((response) => {
        console.log("data", response.data);
        // this.state.products = response.data
        this.setState({
          products: response.data,
        });
      })
      .catch((error) => {
        console.error("错了", error);
      });
  };

  /**
   * del 处理函数
   */
  handleDel = (record: IProduct) => {
    axios({
      method: "DELETE",
      url: `http://localhost:3000/products/${record.id}`,
    })
      .then(() => {
        // 删除成功，重新调用 fetchData
        this.fetchData();
      })
      .catch((error) => {
        console.error("错了", error);
      });
  };

  handleEdit = (record: IProduct, type: "increment" | "decrement") => {
    // 根据 type 计算出要修改的 count
    const newCount = type === "increment" ? record.count + 1 : record.count - 1;
    // 如果 newCount 为 0 表示当前这条数据要删除
    if (newCount === 0) {
      this.handleDel(record);
      return;
    }

    axios<unknown, unknown, Pick<IProduct, "count">>({
      method: "PATCH",
      url: `http://localhost:3000/products/${record.id}`,
      data: {
        count: newCount,
      },
    })
      .then(() => {
        // 修改成功，重新调用 fetchData
        this.fetchData();
      })
      .catch((error) => {
        console.error("错了", error);
      });
  };

  componentDidMount() {
    // 组件挂载完成，调用一次 fetchData
    this.fetchData();
  }

  render() {
    return (
      <div>
        <table className="tb">
          <thead>
            <tr>
              <th>
                <input type="checkbox" name="" id="" />
              </th>
              <th>产品图片</th>
              <th>产品Id</th>
              <th>品牌名称</th>
              <th>价格</th>
              <th>数量</th>
              <th>操作</th>
            </tr>
          </thead>

          <tbody>
            {this.state.products.map((item) => (
              <tr key={item.id}>
                <td>
                  <input type="checkbox" name="" id="" />
                </td>
                <td>
                  <img src={item.imgSrc} alt="" />
                </td>
                <td>{item.id}</td>
                <td>{item.productName}</td>
                <td>{item.price}</td>
                <td>
                  <button onClick={() => this.handleEdit(item, "decrement")}>
                    -
                  </button>
                  {item.count}
                  <button onClick={() => this.handleEdit(item, "increment")}>
                    +
                  </button>
                </td>
                <td>
                  <button onClick={() => this.handleDel(item)}>删除</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    );
  }
}
